<template>
  <div class="wishlist-page">
    <header class="page-header">
      <h1>我的城市心愿清单</h1>
      <p class="sub">查看并管理你收藏的城市</p>
      <div class="header-actions">
        <button class="back-btn" @click="goBack">返回城市特色</button>
      </div>
    </header>

    <section v-if="!isLoggedIn" class="login-tip">
      <p>你尚未登录，展示本地心愿清单。登录后将自动同步至服务器。</p>
    </section>

    <section class="summary" v-if="!loading">
      <span>已收藏 {{ filteredCities.length }} 个城市</span>
    </section>

    <section v-if="error" class="error">{{ error }}</section>

    <section v-if="loading" class="loading">正在加载心愿清单...</section>

    <section v-else class="cities-grid">
      <div v-if="filteredCities.length === 0" class="empty">暂无收藏的城市</div>
      <div 
        v-for="city in filteredCities" 
        :key="city.id" 
        class="city-card"
      >
        <div class="city-image" @click="goToCityDetail(city.id)">
          <img :src="city.image" :alt="city.name" loading="lazy" />
          <div class="city-overlay">
            <span class="city-rating">⭐ {{ city.rating }}</span>
          </div>
        </div>
        <div class="city-info">
          <h3 class="city-name">{{ city.name }}</h3>
          <p class="city-description">{{ city.description }}</p>
          <div class="city-tags">
            <span v-for="tag in city.tags" :key="tag" class="tag">{{ tag }}</span>
          </div>
          <div class="actions">
            <button class="remove-btn" @click="removeCity(city.id)">取消收藏</button>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import { getCities } from '../../api/city'
import { getWishlist, removeFromWishlist } from '../../api/wishlist'
import { authUtils } from '../../utils/auth'

export default {
  name: 'MyWishlist',
  data() {
    return {
      loading: true,
      error: '',
      cities: [],
      wishlistIds: [],
    }
  },
  computed: {
    isLoggedIn() {
      return authUtils.isLoggedIn()
    },
    filteredCities() {
      return this.cities.filter(c => this.wishlistIds.includes(c.id))
    }
  },
  async mounted() {
    await this.loadWishlist()
    await this.fetchCities()
    this.loading = false
  },
  methods: {
    async loadWishlist() {
      const fallback = () => {
        try {
          const raw = localStorage.getItem('cityWishlist')
          const arr = JSON.parse(raw || '[]')
          this.wishlistIds = Array.isArray(arr) ? arr : []
        } catch (e) {
          this.wishlistIds = []
        }
      }
      if (this.isLoggedIn) {
        try {
          const ids = await getWishlist()
          this.wishlistIds = Array.isArray(ids) ? ids : []
        } catch (err) {
          console.error('获取心愿单失败:', err)
          fallback()
        }
      } else {
        fallback()
      }
    },
    async fetchCities() {
      try {
        const list = await getCities()
        this.cities = Array.isArray(list) ? list : []
      } catch (e) {
        console.error('获取城市列表失败:', e)
        this.cities = []
      }
    },
    async removeCity(cityId) {
      if (this.isLoggedIn) {
        try {
          await removeFromWishlist(cityId)
          this.wishlistIds = this.wishlistIds.filter(id => id !== cityId)
        } catch (err) {
          console.error('取消收藏失败:', err)
          this.error = '取消收藏失败，请稍后重试'
        }
      } else {
        // 本地模式
        const raw = localStorage.getItem('cityWishlist')
        const arr = JSON.parse(raw || '[]')
        const next = arr.filter(id => id !== cityId)
        localStorage.setItem('cityWishlist', JSON.stringify(next))
        this.wishlistIds = next
      }
    },
    goToCityDetail(cityId) {
      this.$router.push(`/city/${cityId}`)
    },
    goBack() {
      this.$router.push('/city')
    }
  }
}
</script>

<style scoped>
.wishlist-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}
.page-header {
  margin-bottom: 20px;
}
.page-header h1 {
  font-size: 28px;
  margin: 0 0 6px 0;
}
.sub { color: #666; }
.header-actions { margin-top: 10px; }
.back-btn {
  padding: 8px 14px;
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 6px;
  cursor: pointer;
}
.back-btn:hover { background: #f7f7f7; }
.summary { margin: 10px 0 20px; color: #666; }
.loading, .error, .empty { margin: 20px 0; color: #999; }
.cities-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 20px;
}
.city-card {
  border: 1px solid #eee;
  border-radius: 12px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 4px 12px rgba(0,0,0,0.04);
}
.city-image { position: relative; height: 160px; overflow: hidden; cursor: pointer; }
.city-image img { width: 100%; height: 100%; object-fit: cover; }
.city-overlay { position: absolute; right: 8px; top: 8px; background: rgba(0,0,0,0.5); color: #fff; padding: 4px 8px; border-radius: 6px; }
.city-info { padding: 12px; }
.city-name { margin: 0 0 6px; font-size: 18px; }
.city-description { color: #666; font-size: 14px; margin-bottom: 10px; }
.city-tags { margin-bottom: 10px; }
.tag { display: inline-block; margin-right: 6px; padding: 4px 8px; background: #f5f5f5; border-radius: 6px; font-size: 12px; color: #555; }
.actions { display: flex; justify-content: flex-end; }
.remove-btn { border: 1px solid #ff8a65; color: #ff8a65; padding: 6px 10px; background: #fff; border-radius: 6px; cursor: pointer; }
.remove-btn:hover { background: #fff5f0; }
</style>